package cn.yuxiaoyuan.system.controller;

import cn.yuxiaoyuan.annotation.PreAuthorize;
import cn.yuxiaoyuan.system.domain.Menu;
import cn.yuxiaoyuan.system.query.MenuQuery;
import cn.yuxiaoyuan.system.service.MenuService;
import cn.yuxiaoyuan.utils.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @PreAuthorize(sn = "menu:findById",name = "根据id查询菜单",descs = "根据id查询菜单")
    @GetMapping("/{id}")
    public R findById(@PathVariable("id") Long id) {
        return R.ok(menuService.findById(id));
    }

    @PreAuthorize(sn = "menu:findAll",name = "查询所有菜单",descs = "查询所有菜单")
    @GetMapping
    public R findAll() {
        return R.ok(menuService.findAll());
    }

    @PreAuthorize(sn = "menu:deleteById",name = "根据id删除菜单",descs = "根据id删除菜单")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable("id") Long id) {
        menuService.deleteById(id);
        return R.ok();
    }

    @PreAuthorize(sn = "menu:deleteAll",name = "根据ids删除菜单",descs = "根据ids删除菜单")
    @PostMapping("/deleteAll")
    public R batchDelete(@RequestBody List<Long> ids) {
        menuService.batchDelete(ids);
        return R.ok();
    }

    @PreAuthorize(sn = "menu:add",name = "添加和修改菜单",descs = "添加和修改菜单")
    @ApiOperation("添加和修改")
    @PostMapping
    public R add(@RequestBody Menu menu) {
        if (menu.getId() == null) {
            menuService.add(menu);
        } else {
            menuService.update(menu);
        }
        return R.ok();
    }

    @PreAuthorize(sn = "menu:getPage",name = "菜单的分页查询",descs = "菜单的分页查询")
    @PostMapping("/page")
    public R getPage(@RequestBody MenuQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<Menu> menus = menuService.queryPage(query);
        PageInfo<Menu> pageInfo = new PageInfo<>(menus);
        return R.ok(pageInfo);
    }

    @PreAuthorize(sn = "menu:menuTree",name = "菜单树",descs = "菜单树")
    @GetMapping("/menuTree")
    public R menuTree(){
        return R.ok(menuService.menuTree());
    }
}
